<template>
  <view class="activity-detail">
    <!-- #ifdef H5 -->
    <AppShare ref="share" isHerf title="荣耀活动" />
    <!-- #endif -->
    <view class="activity-top">
      <text v-if="activityData.residueDay > 0" class="status not-start">
        距离活动开始还有:
        <text class="days">{{ activityData.residueDay }}天</text>
      </text>
      <text v-else-if="activityData.residueDay === 0" class="status ing">
        活动进行中
      </text>
      <text v-else class="status ended">活动已结束 </text>
      <activity-item :activity-item="activityData" />
    </view>
    <view class="activity-desc">
      <up-tabs
        :list="activityDescTabs"
        :current="curActivityDescTab"
        :line-width="rpx2px(72)"
        :lineColor="'#00B588'"
        :line-height="rpx2px(9)"
        :itemStyle="activityDescTabStyle"
        @change="handleActivityDescTabChange"
        :activeStyle="{
          color: '#303133',
          fontWeight: 'bold',
          transform: 'scale(1.05)',
        }"
      />

      <view v-if="activityDescTabs[curActivityDescTab].name === '活动介绍'" class="desc">
        <template v-if="activityData.photoArr?.length > 0">
          <view
            class="desc-img"
            v-for="item in activityData.photoArr"
            :key="item"
          >
            <image
              @click="baochun(item)"
              class="img"
              :src="item"
              :show-menu-by-longpress="true"
              mode="widthFix"
            >
            </image>
          </view>
        </template>
        <none-data v-else />
      </view>
      <view v-else class="rule">
<!--        <text class="rule-tips">
          参加活动前请务必仔细阅读本活动贴以及以下须知，逐项确认全部OK再参加活动。参加活动后即表示全部知悉井接受。
        </text>-->
        <!-- {{ curText }} -->

        <up-parse style="line-height: 60rpx;" :content="activityData.activityRule"></up-parse>
        <!-- <text>{{ activityData.activityRule }}</text> -->
        <!-- <rich-text :nodes="curText"></rich-text> -->
        <!-- <view class="rule-main">
          {{ activityData.activityRule }}
        </view> -->
      </view>
    </view>
    <!-- <view class="fixed-btn-group" v-if="true">

      <view class="btn share" @click="ShareClick"> 分享 </view>

      <view
        v-if="activityData.residueDay !== 0 && activityData.joinStatus == 1"
        class="btn sign-up"
        @tap="handleSignUpBtnClick"
      >
        报名
      </view>

      <view class="btn hand" v-else @tap="handleHandClick"> 报名 </view>
    </view> -->
	<view class="foot">
		<view class="box">
			<view class="btn_l" @click="handleShare">
				分享
			</view>
			<view v-if="!isSignUp" class="btn_r" @click="handleSignUpBtnClick">
        {{activityData.activityType === '打卡挑战' ? "去打卡" : "立即报名"}}
			</view>
      <view v-else class="btn_r" @click="registered">
        {{activityData.activityType === '打卡挑战' ? "去打卡" : "已报名"}}
      </view>
		</view>
	</view>
	<view v-if="showShare" class="share" :class="showShare?'share-in':'share-out'">
		<view class="title">
			分享至
		</view>
		<view class="btn">
			<view class="pic">
				<image src="https://honor-hall.oss-cn-chengdu.aliyuncs.com/02.png" mode="aspectFill"></image>
				<button class="sh" open-type="share">微信</button>
			</view>
			<view class="pic">
				<image src="https://honor-hall.oss-cn-chengdu.aliyuncs.com/01.png" mode="aspectFill"></image>
				<button class="sh" @click="handleGroup">朋友圈</button>
			</view>
		</view>

	</view>
	<view v-if="showShare" @click="handleClose" :class="showShare?'mask':''">

	</view>
    <!-- 登录弹窗 -->
    <loginDialog v-if="isShare<1"
      @on-off="headelOff"
      @on-make="headelMake"
      :indicate="userLoginDialog"
    >
    </loginDialog>
  </view>

  <up-popup :show="groupShow" mode="center" border-radius="10px"  @close="groupShow = false" @open="groupShow = true">
    <view>
      <image :show-menu-by-longpress="true" class="contact-us" :src="activityData.wechatGroupImgUrl"></image>
      <view class="contact-us-msg">长按识别二维码，加入群聊，一起了解更多活动进度吧！</view>
    </view>
  </up-popup>
</template>

<script setup>
import loginDialog from "@/components/login/index.vue";
import { ref } from "vue";
import {onLoad, onShareAppMessage, onShareTimeline, onShow} from "@dcloudio/uni-app";
import {
  getUrlParamsInH5,
  getUrlParamsInWeixin,
  rpx2px,
  wxSetUpShareFunction,
} from "../../utils/utils";
import ActivityItem from "../components/activity-item.vue";
import {
  getActivityDetailApi,
  getActivityDetailTicketTotalApi,
  downloadFileApi,
  userSubmitSignUpActivityFormApi,
  getUserSignUpActivityDetailApi, isSignUpApi
} from "../../api/activity";
import AppShare from "@/components/appShare/index.vue";
import { customNav } from "../../utils/customNav";
// const { proxy } = getCurrentInstance();
const userLoginInfo = ref("");
const userLoginDialog = ref(false);
const isShare = ref(0)
const activityData = ref({});
const activityStatusDict = {
  "-1": "notStart",
  0: "ing",
  1: "ended",
};
const curText = ref(``);
const activityDescTabs = ref([{ name: "活动介绍" }, { name: "活动规则" }]);
const curActivityDescTab = ref(0);
const activityDescTabStyle = {
  fontFamily: "ali-p",
  fontSize: "31rpx",
  height: "80rpx!important",
  justifyContent: "flex-start",
  width:'125rpx',
};
const showShare = ref(false)
async function baochun(url) {
  // const res = await downloadFileApi({
  //   type:2,
  //   url:url.replace("https://minio.gzryzl.com/huatai", "")
  // })
  // const { code ,data} = res || {}
  // console.log(data);

  uni.downloadFile({
    url: url, // 图片的URL
    success: async (res) => {
      console.log(res);

      if (res.statusCode === 200) {
        uni.saveImageToPhotosAlbum({
          filePath: res.tempFilePath, // 下载后的临时文件路径
          success: () => {
            console.log("保存成功");
            uni.showToast({
              icon: "none",
              title: "保存成功",
            });
          },
          fail: (error) => {
            console.log("保存失败", error);
          },
        });
      }
    },
    fail: (error) => {
      console.log("下载失败", error);
    },
  });
}
const handleGroup = () => {
	uni.showToast({
		icon:'none',
		title:'点击右上角胶囊按钮分享到朋友圈'
	})
}
const handleShare = () => {
	showShare.value = true
}
const handleClose = () => {
	showShare.value = false
}
function getBASE64Image(img) {
  var canvas = document.createElement("canvas");
  canvas.width = img.width;
  canvas.height = img.height;
  var ctx = canvas.getContext("2d");
  ctx.drawImage(img, 0, 0, img.width, img.height);
  var dataURL = canvas.toDataURL("inage/png");
  return dataURL;
}
function saveImage(url) {
  // console.log("sssssssssssssss");
  // var img = new Image();
  // img.src = url;
  // img.setAttribute("crossOrigin",'Anonymous')
  // img.onload = function () {
  //   var base64 = getBASE64Image(img);
  //   var a = document.createElement("a");
  //   a.href = base64;
  //   a.click()
  // }
}
/**
 * 活动介绍，活动规则切换事件监听
 * @param tab
 */
const handleActivityDescTabChange = (tab) => {
  curActivityDescTab.value = tab.index;
}
function headelOff () {
  userLoginDialog.value = false;
}
function headelMake () {
  userLoginDialog.value = false;
  userLoginInfo.value = uni.getStorageSync("token");
}

const today = new Date()
const year = today.getFullYear();
const month = ('0' + (today.getMonth() + 1)).slice(-2);
const day = ('0' + today.getDate()).slice(-2);
const hours = ('0' + today.getHours()).slice(-2);
const minutes = ('0' + today.getMinutes()).slice(-2);
const seconds = ('0' + today.getSeconds()).slice(-2);
const dateStr = `${year}-${month}-${day}`
const timeStr = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
const startDate = ref('')
/**
 * 报名按钮点击事件监听
 */
const handleSignUpBtnClick = async () => {
  userLoginInfo.value = uni.getStorageSync("token");
  if (!userLoginInfo.value) {
    // userLoginDialog.value = true;
    uni.showModal({
      title: '提示',
      content: '需要登录完善信息，是否去登录？',
      success: function(res) {
        if (res.confirm) {
          uni.navigateTo({ url: "/package_login/pages/login/login" })
        }
      }
    })
  } else {
    if(activityData.value.applyStartTime > timeStr) {
      uni.showToast({
        icon:'error', title: '未到报名时间'
      })
    } else {
      if(activityData.value.isApplyShow === 1) {
        /*uni.showActionSheet({
          title: '请选择您的单位类型',
          itemList: ['机关', '企业'],
          success: function (res) {
            console.log('选中了第' + (res.tapIndex + 1) + '个按钮')
            customNav(`activity-sign-up?activityId=${activityData.value.id}&enterpriseType=` + (res.tapIndex + 1))
          },
          fail: function (res) {
            console.log(res.errMsg);
          }
        })*/
        customNav(`activity-sign-up?activityId=${activityData.value.id}`)
        // customNav(`activity-sign-up?activityId=${activityData.value.id}&enterpriseType=${enterpriseType.value}`)
      } else {
        await uni.showLoading({
          title: "正在报名...",
        });
        const params = {
          activityId: activityData.value.id
        };
        console.log("报名参数",params);
        const res = await userSubmitSignUpActivityFormApi(params);
        console.log(111111111111111111)
        console.log(res)
        const { code, data } = res;
        if (code === 200) {
          setTimeout(() => {
            uni.hideLoading();
            uni.showToast({
              title: '报名成功',
              duration: 2000
            });
            setTimeout(() => {
              isSignUp.value = true
              // groupShow.value = true
            }, 2000)

            if(activityData.value.activityType === '打卡挑战') {
              registered()
            }
          }, 1000)
        } else if (code === 400) {
          uni.hideLoading();
        }
      }
    }
  }
}

function handleHandClick() {
  if (activityData.value.joinStatus == 0) {
    uni.showToast({
      icon: "none",
      title: "您已报名该活动",
    });
  } else {
    uni.showToast({
      icon: "none",
      title: "活动已无法报名",
    });
  }
}
const getActivityDetailData = async () => {
  const res = await getActivityDetailApi(activityData.value.id);
  const { code, data } = res;
  if (code === 200) {
    data.residueDay = !!data.residueDay ? Number(data.residueDay) : 0;
    activityData.value = { ...data };

    curText.value = [
      {
        name: "view",
        attrs: {
          class: "rule-main",
        },
        children: [
          {
            type: "text",
            text: activityData.value.activityRule,
          },
        ],
      },
    ];

    if(data.isApplyShow === 1 && data.serialNumber) {
      uni.showModal({
        title: '报名成功',
        showCancel: false,
        content: '您的报名序号是: ' + data.serialNumber,
        success: function (res) {
          if (res.confirm) {
            console.log('用户点击确定');
          } else if (res.cancel) {
            console.log('用户点击取消');
          }
        }
      })
    }
  }
};

let isSignUp = ref(false)
const getUserSignUpActivityDetail = async () => {
  const res = await isSignUpApi(activityData.value.id)
  const {code, data} = res
  if (code === 200) {
    isSignUp.value = data
  }
}

const registered = () => {
  groupShow.value = false
  if(activityData.value.activityType === '打卡挑战') {
    customNav(`activity/activity-progress?id=${activityData.value.id}`)
  }
}

// function ShareClick() {
//   proxy.$refs.share.open();
// }
onShareAppMessage(()=>{
	return {
		title:activityData.value.activityName,
		path:`/package_activity/pages/activity-detail?isShare=1&id=${activityData.value.id}`,
		imageUrl:activityData.value.activityPoster
	}
})

onShareTimeline(()=>{
	return {
		title:activityData.value.activityName,
		imageUrl:activityData.value.activityPoster
	}
})

const option = ref({}), customNavStatus = ref(true)
onShow(() => {
  uni.setStorageSync("is_view_activity", '1')
  /* #ifdef MP-WEIXIN */
  if(getUrlParamsInWeixin()?.id) {
    activityData.value.id = getUrlParamsInWeixin()?.id;
  }
  isShare.value = getUrlParamsInWeixin()?.isShare
  wxSetUpShareFunction();
  /* #endif */

  /* #ifdef H5 */
  if(getUrlParamsInH5()?.id) {
    activityData.value.id = getUrlParamsInH5()?.id;
  }
  isShare.value = getUrlParamsInH5()?.isShare
  /* #endif */

  getActivityDetailData().then(() => {
    getUserSignUpActivityDetail().then(() => {
      if(isSignUp.value && customNavStatus.value && isSignUp.value && activityData.value.activityType === '打卡挑战') {
        customNavStatus.value = false
        /*customNav(`activity/activity-progress?id=${activityData.value.id}`)*/
      }
    })
  })
});

let enterpriseType = ref('0')
onLoad((options) => {
  // let a  = '1922184755483213826&enterpriseType'
  // console.log(a.indexOf('enterpriseType') !== -1)
  // console.log(a.split('&enterpriseType')[0])
    if (options.q) {
      option.value = JSON.stringify(decodeURIComponent(options.q));
      activityData.value.id = queryLocationParams(
          option.value,
          "activityId"
      ).replace(/"/g, "");

      if(activityData.value.id.indexOf('enterpriseType') !== -1) {
        activityData.value.id = activityData.value.id.split('&enterpriseType')[0]
        enterpriseType.value = '1'
      }
    }
})
const queryLocationParams = (url, variable) => {
  var query = url;
  var vars = query.split("?");
  for (var i = 0; i < vars.length; i++) {
    var pair = vars[i].split("=");
    if (pair[0] == variable) {
      return pair[1];
    }
  }
  return false;
}
let groupShow = ref(false)
</script>
<style lang=less scoped>
.activity-detail {
  padding-top: 28rpx;
  padding-bottom: 100rpx;
  /* #ifdef MP-WEIXIN */
  padding-bottom: 140rpx;
  /* #endif */
  .activity-top {
    background-color: @color-origin-white;
    padding: 28rpx 31rpx 37rpx 35rpx;

    .status {
      font-family: "ali-p";
      font-weight: 500;
      font-size: 31rpx;
    }

    .ended {
      color: @color-grey-text;
    }

    .ing {
      color: @color-blue-text;
    }

    .not-start {
      color: @color-black-text;
      .days {
        color: @color-green-text;
      }
    }

    :deep(.activity-item) {
      border-bottom: none;
    }
  }

  .activity-desc {
    padding: 0 42rpx 34rpx 44rpx;
    box-sizing: border-box;
    margin-top: 24rpx;
    background-color: @color-origin-white;
    :deep(.desc-img) {
      .img {
        margin-top: 28rpx;
        width: 662rpx;
        height: 330rpx;
        object-fit: fill;
        border-radius: 20rpx;
      }
    }

    .rule {
      font-family: "ali-p";
      margin-top: 35rpx;
      .rule-tips {
        font-weight: 700;
        font-size: 23rpx;
        color: @color-black-text;
        margin-bottom: 20rpx;
        display: block;
      }
      .rule-main {
        margin-top: 31rpx;
        font-size: 23rpx;
        color: @color-grey-text;
      }
    }
    /* #ifdef H5 */
    :deep(.u-tabs__wrapper__nav__item) {
      flex: 1;
    }
    /* #endif */
  }

  .fixed-btn-group {
    position: fixed;
    bottom: 0;
    width: 100vw;
    min-height: 111rpx;
    background-color: @color-origin-white;
    display: flex;
    justify-content: space-around;
    align-items: center;
    /* #ifdef MP-WEIXIN */
    padding-bottom: calc(constant(safe-area-inset-bottom));
    padding-bottom: calc(env(safe-area-inset-bottom));
    /* #endif */
    .btn {
      width: 330rpx;
      height: 65rpx;
      line-height: 65rpx;
      border-radius: 33rpx;
      font-family: "ali-p";
      font-weight: 500;
      text-align: center;
    }
    .share {
      background-color: @color-origin-white;
      border: 1px solid @color-green;
      color: @color-green-text;
    }

    .sign-up {
      background: @linear-gradient-btn;
      color: @color-origin-white;
    }
    .hand {
      background: @color-grey;
      color: @color-origin-white;
    }
  }
  .foot{
  	position: fixed;
  	z-index: 3;
  	bottom: 0;
  	width: 100vw;
  	background-color: #F6F8FC;
  	.box{
  		background-color: #ffffff;
  		width: 100vw;
  		height: 140rpx;
  		margin-top: 20rpx;
  		display: flex;
  		justify-content: space-around;
  		align-items: center;
  		.btn_l{
  			width: 295rpx;
  			height: 60rpx;
  			border: 1rpx solid #00B689;
  			text-align: center;
  			line-height: 60rpx;
  			color: #00B689;
  			border-radius: 50rpx;
  			font-weight: bold;
  		}
  		.btn_r{
  			width: 295rpx;
  			height: 60rpx;
  			text-align: center;
  			line-height: 60rpx;
  			color: #ffffff;
  			border-radius: 50rpx;
  			background: linear-gradient(to right,#01E4BF,#0080DB);
  		}
  	}
  }
  @keyframes popup {
    from {
      height: 160rpx;
    }
    to {
      height: 360rpx;
    }
  }
  @keyframes popout {
    from {
      height: 360rpx;
    }
    to {
      height: 160rpx;
      opacity: 0;
    }
  }
  .share{
  	position: fixed;
  	bottom: 160rpx;
  	height: 360rpx;
  	width: 100vw;
  	background-color: #ffffff;
  	border-radius: 30rpx 30rpx 0 0;
  	display: flex;
  	flex-direction: column;
  	justify-content: flex-start;
  	align-items: center;
  	z-index: 3;
  	.title {
  		width: 100vw;
  		height: 100rpx;
  		text-align: center;
  		line-height: 100rpx;
  		border-bottom: 1rpx solid #eeeeee;
  		margin-bottom: 60rpx;
  	}
  	.btn{
  		display: flex;
  		justify-content: center;
  		align-items: center;

  		.pic{
  			width: 100rpx;
  			height: 100rpx;
			box-shadow: 0 0 30rpx rgba(0,0,0,0.05);
			position: relative;
  			&:last-child{
				margin-left: 100rpx;
  				width: 110rpx;
  				height: 110rpx;
  			}
  			image{
  				width: 100%;
  				height: 100%;
  			}
			.sh{
				width: 100rpx;
				height: 100rpx;
				position: absolute;
				bottom: 0;
				opacity: 0;
			}
  		}
  	}

  	&.share-in {
  	  animation: popup ease 0.5s;
  	}
  	&.share-out {
  	  animation: popout ease-out 0.5s;
  	  height: 0;
  	}
  }
  .mask{
  	position: fixed;
  	z-index: 2;
  	bottom: 0;
  	width: 100vw;
  	height: 100vh;
  	background-color: #000000;
  	opacity: 0.5;
  }
}

.contact-us{
  width: 450rpx;
  height: 450rpx;
  border-radius: 10px;
  margin: 10px;
}

.contact-us-msg {
  text-align: center;
  padding: 10px;
  font-size: 14px;
  width: 200px;
  color: #666666;
}
</style>
